
const dbo = require('../utils/db')
const short_key = require('./short_key')
var common = require('../utils/common.js')

var cache_short_info = []

/**分集合最大长度 */
var cup_len = 10000

module.exports = {
    
    /**
     * 获取长链接信息
     * @param {any} p_short_key
     */
    async get_short_info(p_short_key) {

        for (var i = 0; i < cache_short_info.length; i++) {
            if (cache_short_info[i].url_key == p_short_key) {
                return cache_short_info[i]
            }
        }

        var id = common.safeid2id(p_short_key)
        var afterfix = ""
        if (Math.floor(id / cup_len) > 0) { 
            afterfix="_"+Math.floor(id / cup_len)
        }

        const db = await dbo.db_tts_short_url()
        var result = await db.collection("short_url"+afterfix).findOne({
            url_key: p_short_key
        })

        if (result) {
            //缓存100条
            cache_short_info.splice(0, 0, result)
            if (cache_short_info.length > 100) {
                //移出调101个，保持缓存100个
                cache_short_info.pop()
            }
        }
        return result
    },

    /**
     * 停用该链接
     * @param {any} objid  url_key
     */
    async disable_short_url(objid) {
        const db = await dbo.db_tts_short_url()
        if (typeof objid == "string") {
            var id = common.safeid2id(objid)
            var afterfix = ""
            if (Math.floor(id / cup_len) > 0) {
                afterfix="_"+Math.floor(id / cup_len)
            }
            return await db.collection("short_url"+afterfix).updateOne({ url_key: objid }, {
                $set: {
                    status: 0
                }
            })
        } else {
            return false
        }
    },

    /**
     * 添加一条短链接
     * @param {string} appid
     * @param {string} absolute_url
     * @param {number} time  默认30天
     */
    async add_short_url(appid, absolute_url, time = null) {
        const db = await dbo.db_client()
        const unlock = await common.lock()
        var maxindex = Math.floor(await short_key.get_current_key() / cup_len)
        var lastfindfix = ""
        var last = null
        if (maxindex == 0) {
            last = await db.db().collection("short_url").findOne({
                appid: appid,
                absolute_url: absolute_url
            })
        } else {
            //循环找到对应的集合
            for (var index = 0; index < maxindex; index++){
                var forafterfix = "_"+index
                if (index == 0) {
                    forafterfix=""
                }
                last = await db.db().collection("short_url"+forafterfix).findOne({
                    appid: appid,
                    absolute_url: absolute_url
                })
                if (last) {
                    lastfindfix=forafterfix
                    break
                }
            }
        }
        
        if (last) {
            //存在则获取旧的，并且延长有效期
            await db.db().collection("short_url"+lastfindfix).updateOne({
                _id: last._id
            }, {
                $set: {
                    status: 1,
                    exp_time: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000)
                }
            })
            console.log("LAST SHORT_KEY", last.url_key)
            unlock()
            return last.url_key
        }

        //添加一个
        var curid = await short_key.get_new_key()
        //更新自增key的ID

        var key = common.id2safeid(curid)
        console.log("CREATE SHORT_KEY", curid, key)
        
        //20万数据分一次表保存
        var afterfix=""
        if (Math.floor(curid / cup_len) >0) {
            afterfix="_"+(Math.floor(curid / cup_len))
        }

        await db.db().collection("short_url"+afterfix).insertOne({
            url_key: key,           //使用自增值id获得对应的长URL
            url_id:curid,           //id number
            absolute_url: absolute_url,
            appid: appid,
            exp_time: time ? new Date(time) : new Date(Date.now() + 30 * 24 * 60 * 60 * 1000),
            add_time: new Date(),
            status: 1
        })
        unlock()
        return key
    },

    /**
     * 短链接列表
     * @param {any} appid
     * @param {any} page
     * @param {any} page_size  不可超过1000
     */
    async list_short_url(appid,kw, page, page_size) {
        const db = await dbo.db_tts_short_url()
        var list2 = []
        
        var where = {
            appid: appid
        }
        if (kw) {
            where['absolute_url']=new RegExp(kw)
        }
        
        //查出所有需要用到的表，吧分页定位到某个表进行数据查询，有可能跨表，所以顶多夸一个表，每页的长度不能超过2个表的长度/2
        var maxid = await short_key.get_current_key()
        
        var len_list = []
        var total = 1
        var count = 0
        for (var i = 0; i <= Math.floor(maxid / cup_len); i++){
            var afterfix = ""
            if (i > 0) {
                afterfix="_"+i
            }
            var len = await db.collection("short_url" + afterfix).countDocuments(where)
            
            len_list.push({
                max_len: len,
                min_page:total,
                max_page:Math.ceil(len/page_size) //最大页数
            })
            total += Math.ceil(len / page_size)
            count+=len
        }
        var curpage_index = (page - 1) * page_size
        
        var curpage_index_table_fix = ""
        var next_curpage_index_table_fix=""
        
        for (var i = 0; i < len_list.length; i++){
            if(page>=len_list[i].min_page &&
                page <len_list[i].min_page+ len_list[i].max_page ) {
                curpage_index_table_fix = "_"+i
                if (curpage_index_table_fix == "_0") {
                    curpage_index_table_fix=""
                }
                next_curpage_index_table_fix = "_" + (i + 1)
                //上一个集合最后不足cup_len的值
                var lasttable_fx = (i>0 ? (cup_len- len_list[i-1].max_len) : 0)
                curpage_index = ((page - len_list[i].min_page)*page_size) + lasttable_fx
                break
            }
        }
        


        await db.collection("short_url"+curpage_index_table_fix).find(where).skip(curpage_index).limit(page_size).sort({
            add_time:1
        }).forEach((info) => {
            info._id = info._id.toHexString()
            list2.push(info)
        })

        if (list2.length < page_size) {
            //curpage_index_table_fix 肯定是大于0的
            await db.collection("short_url"+next_curpage_index_table_fix).find({
                appid: appid
            }).skip(0).limit(page_size - list2.length).forEach((info) => {
                info._id = info._id.toHexString()
                list2.push(info)
            })
        }


        return [list2,count]
    },

    /**
     * 更新跳转次数
     * @param {any} urlkey
     * @param {any} num
     */
    async inser_short_jump_num(urlkey, num) {
        const db = await dbo.db_tts_short_url()
        var unlock = await common.lock()
        
        var id = common.safeid2id(urlkey)
        var afterfix = ""
        if (Math.floor(id / cup_len) > 0) {
            afterfix="_"+Math.floor(id / cup_len)
        }

        var res = await db.collection("short_url"+afterfix).findOne({ url_key: urlkey })
        await db.collection("short_url"+afterfix).updateOne({ url_key: urlkey }, {
            $set: {
                num: res['num'] ? res['num'] + num : num
            }
        })
        unlock()
    }
}